package com.zf.shuashua.video;

import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.aliyun.player.AliPlayer;
import com.aliyun.player.AliPlayerFactory;
import com.aliyun.player.IPlayer;
import com.aliyun.player.source.UrlSource;
import com.zf.shuashua.ShuaApplication;

/**
 * 视频播放
 */
public class VideoPlayManager {

    private AliPlayer aliPlayer;

    private static VideoPlayManager instance;

    private VideoPlayManager() {

    }

    public static VideoPlayManager getInstance() {
        if (null == instance) {
            synchronized (VideoPlayManager.class) {
                if (null == instance) {
                    instance = new VideoPlayManager();
                }
            }
        }
        return instance;
    }

    public void startPlay(String url, SurfaceView surfaceView){
//        if(aliPlayer == null){
//            aliPlayer = AliPlayerFactory.createAliPlayer(ShuaApplication.getContext());
//        }else{
//            aliPlayer.stop();
//        }
        aliPlayer = AliPlayerFactory.createAliPlayer(ShuaApplication.getContext());
        surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                if (aliPlayer != null) {
                    aliPlayer.setDisplay(holder);
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                if (aliPlayer != null) {
                    aliPlayer.redraw();
                }
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                if (aliPlayer != null) {
                    aliPlayer.setDisplay(null);
                }
            }
        });

        UrlSource urlSource = new UrlSource();
        urlSource.setUri(url);

        aliPlayer.setDataSource(urlSource);
        aliPlayer.setOnCompletionListener(() -> {
            //播放完成
        });
        aliPlayer.setOnErrorListener(errorInfo -> {
            //出错事件
        });
        aliPlayer.setOnPreparedListener(() -> {
            //准备成功事件
        });
        aliPlayer.setOnRenderingStartListener(() -> {
            //首帧渲染显示
        });
        aliPlayer.setScaleMode(IPlayer.ScaleMode.SCALE_ASPECT_FIT);
        aliPlayer.prepare();

        aliPlayer.start();

    }

}
